// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
var fs = require("fs");
import { win32 } from "path";
import path = require("path");
import * as vscode from "vscode";
import utils from "./utils/utils";

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
  // Use the console to output diagnostic information (console.log) and errors (console.error)
  // This line of code will only be executed once when your extension is activated
  console.log('Congratulations, your extension "imgtogitee" is now active!');

  // The command has been defined in the package.json file
  // Now provide the implementation of the command with registerCommand
  // The commandId parameter must match the command field in package.json
  let emoCommand = vscode.commands.registerCommand(
    "imgtogitee.getemo",
    async () => {
      let emo = utils.getemo();
      utils.insertToEnd(emo);
    }
  );
  let pasteLocalCommand = vscode.commands.registerCommand(
    "imgtogitee.pasteLocal",
    async () => {
      try {
        // eslint-disable-next-line @typescript-eslint/naming-convention
        let gitee_token = vscode.workspace
          .getConfiguration()
          .get("imgtogitee.gitee_token");
        if (gitee_token + "" === "") {
          vscode.window.showErrorMessage("token 不能为空嗷");
        }
        console.log(gitee_token);

        // eslint-disable-next-line @typescript-eslint/naming-convention
        let gitee_url = vscode.workspace
          .getConfiguration()
          .get("imgtogitee.gitee_url");
        if (gitee_url + "" === "") {
          vscode.window.showErrorMessage("gitee url 不能为空嗷");
        }
        console.log(gitee_url);
        const edit = vscode.window.activeTextEditor;
        if (!edit) {
          vscode.window.showErrorMessage("没有打开编辑窗口");
          return;
        }
        vscode.window
          .showOpenDialog({
            filters: { Images: ["png", "jpg", "gif", "bmp"] },
          })
          .then(async (result) => {
            if (result) {
              const { fsPath } = result[0];
              console.log(fsPath);
              let baseURL = await utils.imgtobase64(fsPath);
              // console.log(baseURL);
              //上传图片
              let filename = `pic_${new Date().getTime()}.png`;
              let uploadMsg = await utils.uploadgitee(
                gitee_url + "/" + filename,
                gitee_token + "",
                baseURL + ""
              );

              console.log(uploadMsg.content["download_url"]);

              let mdurl = `![${filename}](${uploadMsg.content["download_url"]} '${utils.pkg.name}')`;
              console.log(mdurl);
              utils.insertToEnd(mdurl);
            }
          });
      } catch (error: any) {
        vscode.window.showErrorMessage(`上传失败：${error.message}`);
      }
    }
  );
  function padTo2Digits(num: number) {
    return num.toString().padStart(2, '0');
  }
  function formatDate(date: Date) {
    return (
      [
        date.getFullYear(),
        padTo2Digits(date.getMonth() + 1),
        padTo2Digits(date.getDate()),
      ].join('-') 
    );
  }
  // 把图片从剪切板存到临时文件夹
  // 再从临时文件夹上传到gitee仓库，实现图床功能
  let pasteCommand = vscode.commands.registerCommand(
    "imgtogitee.paste",
    async () => {
      // utils.execps1();
      // let savePath = utils.getTmpFolder();
      // console.log(savePath);
      // let savePath = path.join(__dirname, '..', `asserts/pic_${new Date().getTime()}.png`);

      try {
        // eslint-disable-next-line @typescript-eslint/naming-convention
        let gitee_token = vscode.workspace
          .getConfiguration()
          .get("imgtogitee.gitee_token");
        if (gitee_token + "" === "") {
          vscode.window.showErrorMessage("token 不能为空嗷");
        }
        console.log(gitee_token);

        // eslint-disable-next-line @typescript-eslint/naming-convention
        let gitee_url = vscode.workspace
          .getConfiguration()
          .get("imgtogitee.gitee_url");
        if (gitee_url + "" === "") {
          vscode.window.showErrorMessage("gitee url 不能为空嗷");
        }
        console.log(gitee_url);

        let savePath = path.join(__dirname, "..", `asserts/`);
        console.log(savePath);

        let filename = `${new Date().getTime()}.png`;
        savePath = path.resolve(savePath, filename);
        let images = await utils.getPasteImage(savePath);
        images = images.filter((img) =>
          [".jpg", ".jpeg", ".gif", ".bmp", ".png", ".webp", ".svg"].find(
            (ext) => img.endsWith(ext)
          )
        );
        if (images.length <= 0) {
          vscode.window.showWarningMessage("未找到图片");
        }
        for (let i = 0; i < images.length; i++) {
          console.log(images[i]);

          let baseURL = await utils.imgtobase64(images[i]);
          // console.log(baseURL);
          let uploadMsg = await utils.uploadgitee(
            gitee_url + "/pictures/" + formatDate(new Date())+ "/" + filename,
            gitee_token + "",
            baseURL + ""
          );

          console.log(uploadMsg.content["download_url"]);

          let mdurl = `![${filename}](${uploadMsg.content["download_url"]})`;
          console.log(mdurl);
          utils.insertToEnd(mdurl);

          fs.unlink(savePath, function () {});

          // vscode.window.showInformationMessage("上传成功");
        }
      } catch (error: any) {
        vscode.window.showErrorMessage(`上传失败：${error.message}`);
      }
    }
  );
  context.subscriptions.push(emoCommand);
  context.subscriptions.push(pasteCommand);
  context.subscriptions.push(pasteLocalCommand);
}

export function deactivate() {}
